#!/usr/bin/env node

/**
 * Simple Security Check
 *
 * 基础安全检查 - 专为本地MCP工具设计
 */

const fs = require('fs');
const path = require('path');

class SimpleSecurityChecker {
    constructor() {
        this.projectRoot = process.cwd();
        this.issues = [];
        this.warnings = [];
    }

    /**
     * Run basic security checks
     */
    async runChecks() {
        console.log('🔒 Running basic security checks...\n');

        // Check for sensitive files
        this.checkSensitiveFiles();

        // Check dependencies
        await this.checkDependencies();

        // Check configuration
        this.checkConfiguration();

        this.printResults();
        return this.issues.length === 0;
    }

    /**
     * Check for sensitive files in repository
     */
    checkSensitiveFiles() {
        const sensitiveFiles = [
            '.env',
            '.env.local',
            'config.json',
            'secrets.json',
            'private-key.pem',
            'id_rsa'
        ];

        sensitiveFiles.forEach(file => {
            const filePath = path.join(this.projectRoot, file);
            if (fs.existsSync(filePath)) {
                this.warnings.push(`Sensitive file found: ${file}`);
            }
        });
    }

    /**
     * Check package.json for known vulnerabilities
     */
    async checkDependencies() {
        try {
            const packagePath = path.join(this.projectRoot, 'package.json');
            if (fs.existsSync(packagePath)) {
                const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
                console.log('✓ package.json found and readable');
            }
        } catch (error) {
            this.issues.push('Failed to read package.json');
        }
    }

    /**
     * Check basic configuration security
     */
    checkConfiguration() {
        try {
            const configPath = path.join(this.projectRoot, 'settings.json');
            if (fs.existsSync(configPath)) {
                const config = fs.readFileSync(configPath, 'utf8');

                // Check for plain API keys
                if (config.includes('sk-') || config.includes('sg-')) {
                    this.warnings.push('Configuration may contain API keys');
                }

                console.log('✓ Configuration file checked');
            }
        } catch (error) {
            this.issues.push('Failed to check configuration');
        }
    }

    /**
     * Print check results
     */
    printResults() {
        console.log('\n📊 Security Check Results:');
        console.log(`Issues: ${this.issues.length}`);
        console.log(`Warnings: ${this.warnings.length}\n`);

        if (this.issues.length > 0) {
            console.log('❌ Issues found:');
            this.issues.forEach(issue => console.log(`  - ${issue}`));
        }

        if (this.warnings.length > 0) {
            console.log('⚠️  Warnings:');
            this.warnings.forEach(warning => console.log(`  - ${warning}`));
        }

        if (this.issues.length === 0 && this.warnings.length === 0) {
            console.log('✅ No security issues found!');
        }
    }
}

// Run security check if called directly
if (require.main === module) {
    const checker = new SimpleSecurityChecker();
    checker.runChecks().then(success => {
        process.exit(success ? 0 : 1);
    }).catch(error => {
        console.error('Security check failed:', error.message);
        process.exit(1);
    });
}

module.exports = SimpleSecurityChecker;